package com.webserver_v5.controller;

import com.webserver_v5.annotation.Controller;
import com.webserver_v5.annotation.RequestMapping;
import com.webserver_v5.http.HttpServletRequest;
import com.webserver_v5.http.HttpServletResponse;
import com.webserver_v5.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class ArticleWriteController {

    @RequestMapping("/writeArticle")
    public void write(HttpServletRequest request , HttpServletResponse response){
        String author = request.getParameters("author");
        String title = request.getParameters("title");
        String content = request.getParameters("content");

        try(
                Connection connection = DBUtil.getConnection();
                ) {
            String sql = "select id from userinfo where username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,author);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                int id = rs.getInt("id");
                sql = "insert into article(title,content,u_id) values (?,?,?)";
                ps = connection.prepareStatement(sql);
                ps.setString(1,title);
                ps.setString(2,content);
                ps.setInt(3,id);
                int n = ps.executeUpdate();
                if (n>0){
                    response.sendRedirect("write_article_success.html");
                }else {
                    response.sendRedirect("write_article_fail.html");
                }
            }else {
                response.sendRedirect("have_not_user.html");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
